package com.ts.api.http.market.channel;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarket;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarketConvertType;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.market.entity.ChannelMarketParameter;
import com.ts.api.module.api.convert.market.handler.ChannelMarketConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 *  乐闪融-UV-联登接口
 *
 *  https://www.showdoc.com.cn/yxhapi 密码123456
 *
 *  @author WJB
 */
@ApiChannelMarket(uniqueCode = "d7187c61d5634f209c55313dfc30d141", type = ApiChannelMarketConvertType.FEDERATE_LOGIN)
public class leShanRongFederate implements ChannelMarketConvertHandler {

    private static final String KEY = "XZ0(sS7*qM2&cX7;KSM%uP51";
    private static final String IV = "2%8iTpSi";
    @Override
    public ApiUserRequest parse(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String sign = jsonObject.getString("sign");
        String data = Decrypt(sign, KEY, IV);
        JSONObject decryptJson = JsonUtils.get(data);
        String phone = decryptJson.getString("phone");

        ApiUserRequest apiUserRequest = new ApiUserRequest();
        apiUserRequest.setPhone(phone);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> response(ChannelMarketParameter channelMarketParameter, ApiBizStatus apiBizStatus) {
        if (apiBizStatus.hasBizSuc()) {
            return MapUtils.newHashMap(newMap -> {
                newMap.put("code", 200);
                newMap.put("message", apiBizStatus.getBizMsg());
                newMap.put("data", MapUtils.newHashMap(data -> {
                    data.put("status", 1);
                    data.put("downUrl", channelMarketParameter.getUrl());
                }));
            });
        }
        return MapUtils.newHashMap(newMap -> {
            newMap.put("code", 400);
            newMap.put("message", apiBizStatus.getBizMsg());
        });
    }

    //  解密
    private static String Decrypt(String encryptedData, String key, String iv) {
        try {
            return dataDes3Decrypt(encryptedData, key, iv);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //  解密
    private static String dataDes3Decrypt(String encryptedData, String key, String iv) throws Exception {
        // URL 解码密文
        String decodedEncryptedData = URLDecoder.decode(encryptedData, StandardCharsets.UTF_8.name());

        // 将解码后的密文转换为字节数组
        byte[] encryptedDataBytes = Base64.getDecoder().decode(decodedEncryptedData);

        // 创建 3DES 解密算法实例
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

        // 创建密钥和 IV 参数
        SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DESede");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));

        // 初始化解密器
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

        // 执行解密操作
        byte[] decryptedData = cipher.doFinal(encryptedDataBytes);

        // 将解密后的数据转换为字符串并返回
        return new String(decryptedData, StandardCharsets.UTF_8);
    }
}
